﻿using HandyControl.Data;
using HW.Application.Share.Events;
using HW.Core.Dialog;
using HW.Core.Helper;
using HW.Core.Ioc;
using HW.Database.SQLServer;
using HW.Database.SQLServer.Repository;
using HW.Logger;
using Prism.Commands;
using Prism.Mvvm;
using ReactiveUI;
using ReactiveUI.Fody.Helpers;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.UI.WebControls;
using System.Windows;
using System.Windows.Input;

namespace HW.Application.Sheet.ViewModels
{
    public class SheetViewModel : ReactiveObject
    {
        

        [Reactive]
        public DateTime StartDate { get; set; }
        [Reactive]
        public DateTime EndDate { get; set; }
        [Reactive]
        public string NumberOfJobsSearch { get; set; }
        [Reactive]
        public string ProductNumberSearch { get; set; }
        public bool isAscending { get; set; }
        [Reactive]
        public int PageIndex { get; set; }
        [Reactive]
        public int PageCount { get; set; }

        public int PageSize { get; set; }



        private FunctionEventArgs<int> info;

        private IRotorInformationRepository RotorInformationRepository { get; }
        
        [Reactive]
        public ObservableCollection<RotorInformation> RotorInformations { get; set; }

        public ICommand ToggleButtonCheckedCommand { get; }
        public ICommand SelectRotorInformationCommand { get; }
        public ICommand ExportRotorInformationCommand { get; }
        public ICommand ResetRotorInformationCommand { get; }
        public ICommand AddRotorInformationCommand { get; }
        public SheetViewModel ()
        {
            RotorInformationRepository = new RotorInformationRepository();
            SelectRotorInformationCommand = new DelegateCommand<FunctionEventArgs<int>>(SelectRotorInformation);
            ResetRotorInformationCommand = new DelegateCommand(ResetRotorInformation);
            ExportRotorInformationCommand = new DelegateCommand(ExportRotorInformation);
            ToggleButtonCheckedCommand = new DelegateCommand(ToggleButtonChecked);

            StartDate = Convert.ToDateTime(DateTime.Now.AddDays(-7).ToString("yyyy-MM-dd 00:00:00"));
            EndDate = Convert.ToDateTime(DateTime.Now.AddDays(1).ToString("yyyy-MM-dd 00:00:00"));
            PageIndex = 1;
            PageCount = 10;
            PageSize = 15;
            NumberOfJobsSearch = null;
            ProductNumberSearch = null;

            PrismProvider.Dispatcher.Invoke(() =>
            {
                PrismProvider.EventAggregator.GetEvent<ShowWindowEvent>().Subscribe(()=>SelectRotorInformation(null));
#if DEBUG
                //PrismProvider.EventAggregator.GetEvent<UpdateHistorySheetEvent>().Subscribe(() => SelectRotorInformation(null));
#endif
            });
        }

        

        //时间排序切换
        private void ToggleButtonChecked()
        {
            isAscending = !isAscending;
            SelectRotorInformation(null);
        }
        //转子历史信息查询
        private async void SelectRotorInformation(FunctionEventArgs<int> info)
        {
            try
            {
                await Task.Run(() =>
                {
                    if (info != null)
                    {
                        PageIndex = info.Info;
                    }

                    var countRows = RotorInformationRepository.CountByConditions(StartDate, EndDate, NumberOfJobsSearch, ProductNumberSearch);

                    PageCount = (countRows + PageSize - 1) / PageSize;

                    var list = RotorInformationRepository.GetByConditions(StartDate, EndDate, NumberOfJobsSearch, ProductNumberSearch, PageIndex, PageSize, isAscending);

                    RotorInformations = new ObservableCollection<RotorInformation>();

                    if (list == null || list.Count == 0)
                    {
                        PrismProvider.Dispatcher.Invoke(() =>
                        {
                            PopupBox.Show("未查到历史数据");
                        });
                        return;
                    }
                    PrismProvider.Dispatcher.Invoke(() =>
                    {
                        for (int i = 0; i < list.Count; i++)
                        {
                            RotorInformations.Add(list[i]);
                            RotorInformations[i].SerialNumber = i + 1 + PageSize * (PageIndex - 1);
                        }
                    });
                    list.Clear();
                });
            }
            catch (Exception ex)
            {
                Logs.LogError(ex);
            }
        }
        //查询页面重置
        private void ResetRotorInformation() {
                StartDate = Convert.ToDateTime(DateTime.Now.AddDays(-7).ToString("yyyy-MM-dd 00:00:00"));
                EndDate = Convert.ToDateTime(DateTime.Now.AddDays(1).ToString("yyyy-MM-dd 00:00:00"));
                PageIndex = 1;
                PageCount = 10;
                PageSize = 15;
                NumberOfJobsSearch = null;
                ProductNumberSearch = null;
                SelectRotorInformation(null);
        }
        //转子信息导出CSV带别名
        private async void ExportRotorInformation()
        {
            try
            {
                await Task.Run(() =>
                {
                    if (RotorInformations == null || RotorInformations.Count == 0)
                    {
                        PrismProvider.Dispatcher.Invoke(() =>
                        {
                            PopupBox.Show("没有历史数据可以导出");
                        });
                        return;
                    }

                    var list = RotorInformationRepository.ExportByConditions(StartDate, EndDate, NumberOfJobsSearch, ProductNumberSearch);

                    if (list.Count > 20000)
                    {
                        PrismProvider.Dispatcher.Invoke(() =>
                        {
                            PopupBox.Show("     数据量过大\r请操作数据库导出", null, 2);
                        });

                        return;
                    }

                    if (FileHelper.SaveFileDialog("导出历史转子数据", "CSV Files|*.csv", ".csv", null, out string fullname))
                    {
                        ObservableCollection<RotorInformation> RotorInformationsExported = new ObservableCollection<RotorInformation>();

                        for (int i = 0; i < list.Count; i++)
                        {
                            RotorInformationsExported.Add(list[i]);
                            RotorInformationsExported[i].SerialNumber = i + 1;
                        }
                        bool exportFinish = ExportHelper.Export(RotorInformationsExported, fullname);
                        PrismProvider.Dispatcher.Invoke(() =>
                        {
                            PopupBox.Show(exportFinish ? "导出成功" : "导出失败");
                        });
                        RotorInformationsExported.Clear();
                    }
                });
            }
            catch (Exception ex)
            {

                Logs.LogError(ex);
            }        
        }

        //#region 添加样例数据

        //private void AddRotorInformation()
        //{

        //    for (int i = 0; i < 10000; i++)
        //    {
        //        var rotorInfo = new RotorInformation
        //        {
        //            CreateDateTime = DateTime.Now,
        //            ProductNumber = GenerateProductNumber(),
        //            NumberOfJobs = GenerateNumberOfJobs(),
        //            UnbalanceAmount1InGrams = GenerateRandomDecimal(),
        //            UnbalanceAmount1InGramsGcm = GenerateRandomDecimal(),
        //            AngleFace1 = GenerateRandomDecimal(),
        //            UnbalanceAmount2InGrams = GenerateRandomDecimal(),
        //            UnbalanceAmount2InGramsGcm = GenerateRandomDecimal(),
        //            AngleFace2 = GenerateRandomDecimal(),
        //            UnbalanceAmount3InGrams = GenerateRandomDecimal(),
        //            UnbalanceAmount3InGramsGcm = GenerateRandomDecimal(),
        //            AngleFace3 = GenerateRandomDecimal(),
        //            UnbalanceAmount4InGrams = GenerateRandomDecimal(),
        //            UnbalanceAmount4InGramsGcm = GenerateRandomDecimal(),
        //            AngleFace4 = GenerateRandomDecimal(),
        //            AllowableError = GenerateRandomDecimal(),
        //        };
        //        bool v = RotorInformationRepository.Insert(rotorInfo);
        //    }
        //    MessageBox.Show("All data inserted successfully.");

        //}



        //static string GenerateProductNumber()
        //{
        //    // Generate your product number here
        //    return "ProductNumber" + Guid.NewGuid().ToString().Substring(0, 8);
        //}

        //static string GenerateNumberOfJobs()
        //{
        //    // Generate your number of jobs here
        //    return "NumberOfJobs" + new Random().Next(1, 100).ToString();
        //}

        //static decimal GenerateRandomDecimal()
        //{
        //    // Generate a random decimal value
        //    Random random = new Random();
        //    decimal value = Math.Round((decimal)(random.NextDouble() * 100), 2);
        //    return value;
        //}
        //#endregion

    }

}
